package com.ydl.shopping.security.handle;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ydl.shopping.core.enums.ResultEnum;
import com.ydl.shopping.core.vo.ResultVO;
import com.ydl.shopping.utils.web.WebUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.ydl.shopping.constant.SystemConstants.AUTHORIZATION;

/**
 * 登录认证错误处理器
 *
 * @author 林武泰
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String header = request.getHeader(AUTHORIZATION);
        ResultVO resultVo = null;

        if (authException.getMessage().equals("Full authentication is required to access this resource")) {
            if (StrUtil.isNotBlank(header)) {
                resultVo = ResultVO.resultEnum(ResultEnum.UNAUTHORIZED);
                resultVo.setMessage("登录认证无效");
            } else {
                resultVo = ResultVO.resultEnum(ResultEnum.UNAUTHORIZED);
                resultVo.setMessage("拒绝访问");
            }
        }
        WebUtil.renderString(response, JSONUtil.toJsonStr(resultVo));
    }
}
